package platform

import (
	"context"
	"fmt"

	"github.com/smartwalle/alipay/v3"
	"github.com/wzh200x/hyperNexus/hyperNexusErr"
	"github.com/wzh200x/hyperNexus/hyperNexusProtocol/interfaceServerProtocol"
	"github.com/wzh200x/hyperNexus/hyperNexusType"
)

// 支付宝登录返回的会话信息
type PlatformAlipay struct {
	PlatformBase
}

func (p *PlatformAlipay) Login(ctx context.Context, input *interfaceServerProtocol.LoginRequest) (output interfaceServerProtocol.LoginResponse, err error) {
	// 1. 通过code获取微信会话信息
	session, err := p.GetSession(input.AppId, input.PrivateKey, input.PublicKey, input.Code)
	if err != nil {
		output.Code = hyperNexusErr.ErrCode_PlatformLoginFailed
		output.Msg = err.Error()
		return output, err
	}
	output.Code = 0
	output.OpenId = session.OpenId
	output.Datas = session.AccessToken

	return output, nil
}

// 通过code获取支付宝会话信息
func (p *PlatformAlipay) GetSession(appid string, privateKey string, publicKey string, code string) (*alipay.SystemOauthTokenRsp, error) {
	client, err := alipay.New(appid, privateKey, true)
	if err != nil {
		return nil, err
	}
	// 换取授权访问令牌
	params := alipay.SystemOauthToken{
		GrantType: "authorization_code",
		Code:      code,
	}
	resp, err := client.SystemOauthToken(context.TODO(), params)
	if err != nil {
		return nil, err
	}

	if resp.Code != "" {
		return nil, fmt.Errorf("支付宝API错误: %s %s", resp.Code, resp.Msg)
	}

	return resp, nil
}

func NewPlatformAlipay() *PlatformAlipay {
	return &PlatformAlipay{
		PlatformBase: PlatformBase{
			PlatformID: hyperNexusType.PlatformTypeAlipay,
		},
	}
}
